<?php
/**
 * Created by PhpStorm.
 * User: 2016-08-23
 * Date: 2017/11/6
 * Time: 10:46
 */
$api_service_path = __DIR__ . "/../../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();
DB::connection()->disableQueryLog(); 
Log::useFiles(storage_path().'/logs/kingdee_push.log');
/**
 * 用于金蝶推送每月结转的 凭证每月 初一 执行
 */
// $mdb=MaintenanceShops::whereIn("id",array(1,3))->get();
$mdb=MaintenanceShops::where("status",1)->where("id","!=",5)->get();//循环各个门店的入库出库各种记录
$date=date('Y-m-t', strtotime('-1 month'));//上个月最后一天

$begin_date=date('Y-m-01 00:00:00', strtotime('-1 month'));
$end_date=date('Y-m-t 23:59:59', strtotime('-1 month'));
// $_date=array("2018-09-01","2018-09-01");



$cli=DB::select("SELECT id,jindie_code FROM `supply_classification` where `level`=1 and `status`=1");
$cli_arr=array();
foreach ($cli as $_c) {
    $cli_arr[$_c->id]=array("jindie_code"=>$_c->jindie_code,"sale_amount"=>0);
}    
foreach ($mdb as $_mdb) {//
    if(!$_mdb->kingdee_groupid){
        Log::error("门店 ".$_mdb->id."金蝶科目部门异常"); 
        continue;
    }
    $xj_msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","1001")->first();//本门店的现金账套
    if(is_null($xj_msk)){
        Log::error("门店 ".$_mdb->id."现金科目异常");
        continue 1;//有错误数据
    }
    $tkvs=KingdeeVoucherStatus::where("date",$date)->where("type","month_jiezhuan")->where("shop_id",$_mdb->id)->where("status",1)->first();
    if($tkvs){//如果该门店 该天已经推送过凭证了
        continue;
    }
    $data=array('mainVoucher' =>
        array( 
        )
    );
    $entty_array=array();//组织所有的最基层 结构
    $inputjie = array(
        "FAccountID"=>"1243",
        "FExplanation"=>"",
        "FCurrencyID"=>1,
        "FExchangeRate"=>1,
        "FDC"=>1,
        "FAmountFor"=>100,
        "FAmount"=>100,
        "data"=>array(
            "009"=>"114",//商品分类
            "012"=>"001",//直营店
        ),
    );
    $inputdai = array(
        "FAccountID"=>"1243",
        "FExplanation"=>"脚本测试1",
        "FCurrencyID"=>1,
        "FExchangeRate"=>1,
        "FDC"=>0,
        "FAmountFor"=>100,
        "FAmount"=>100,
        "data"=>array(
            "009"=>"114",//商品分类
            "012"=>"001",//直营店
        ),
    );
    $temp_arr=$cli_arr;
    /**
     * 获取基础数据
     */    
    $response=Report::get_supply_stock_new($begin_date,$end_date,0,$_mdb->id);
    foreach ($response as $_r) {        
        if(isset($temp_arr[$_r["level_1_id"]])){
            $temp_arr[$_r["level_1_id"]]['sale_amount']=$temp_arr[$_r["level_1_id"]]['sale_amount']+$_r["saleout_amount"]+$_r["orderout_amount"]-$_r["return_into_amount"]+$_r["diaochu_amount_xs"];            
        }else{
            Log::error("门店 ".$_mdb->id."分类异常:".$_r["level_1_id"]); 
            continue 2;
        }  
    }
    unset($response);
    $temp_pz=array();
    foreach ($temp_arr as $_t) {
        if($_t['sale_amount']==0){
            continue;
        }
        $inputjie["FAccountID"]="5401";
        $inputjie["FExplanation"]="结转成本";
        $inputjie["FAmountFor"]=round($_t['sale_amount']/100,2);
        $inputjie["FAmount"]=round($_t['sale_amount']/100,2);

        $inputdai["FAccountID"]="1243";
        $inputdai["FExplanation"]="结转成本";
        $inputdai["FAmountFor"]=round($_t['sale_amount']/100,2);
        $inputdai["FAmount"]=round($_t['sale_amount']/100,2);

        $datejie=array("012"=>$_mdb->kingdee_shopnum);
        $datedai=array("009"=>$_t['jindie_code'],"012"=>$_mdb->kingdee_shopnum);
        
        $inputjie["data"]=$datejie;
        $temp_pz[]=$inputjie;
        $inputdai["data"]=$datedai;
        $temp_pz[]=$inputdai;
    }
    unset($temp_arr);
    //合并贷方
    $depe_temp_dai=null;
    foreach($temp_pz as $key=>$t){
        if($t['FDC']==1){
            if(is_null($depe_temp_dai)){
                $depe_temp_dai=$t;
            }else{
                $depe_temp_dai["FAmountFor"]+=$t['FAmountFor'];
                $depe_temp_dai["FAmount"]+=$t['FAmount'];
            }
            unset($temp_pz[$key]);
        }
    }
    $temp_iyc_amount=array();
    if(!is_null($depe_temp_dai)){
        $temp_iyc_amount[]=$depe_temp_dai;
    }
    $temp_pz=array_merge($temp_iyc_amount,$temp_pz);
    //合并完毕
    
    assembleNotsort($data,$temp_pz,$date,$_mdb);
    unset($temp_pz);
    // Log::info($data);
    if(sizeof($data["mainVoucher"])>0){  
        getMaintain($_mdb->id,$data,$date);
        Log::info("门店".$_mdb->id." 日期 ".$date.'完毕');
        echo "门店".$_mdb->id." 日期 ".$date.'完毕';
    }else{
        Log::info("门店".$_mdb->id." 日期 ".$date.'完毕');
        echo "门店".$_mdb->id." 日期 ".$date.'完毕';
    }  
}

function assembleNotsort(&$finally,$value_array,$date,$_mdb){
    if(sizeof($value_array)==0){     
        return $finally;
    }
    $temp =array(
        "FDate"=>$date." 00:00:00",
        "FGroupID"=>$_mdb->kingdee_groupid,//来广营 6
        "FReference"=>null,
        "FAttachments"=>0,
        "FEntryCount"=>4,
        "FDebitTotal"=>0,
        "FCreditTotal"=>0,
        "FPreparerID"=>16428,//写死的制单人
        "FPosterID"=>-1,
        "FTranType"=>0,
        "FTransDate"=>$date." 00:00:00",
        "entryVoucher"=>array(
            
        )           
    );
    $FEntryCount=0;
    $FDebitTotal=0;
    $FCreditTotal=0;
    foreach ($value_array as $value) {  
        $FEntryCount++;
        $value["FAmountFor"]=round($value["FAmountFor"],2);
        $value["FAmount"]=round($value["FAmount"],2);
        if($value["FDC"]==1){
            $FDebitTotal+=$value["FAmountFor"];
        }else{
            $FCreditTotal+=$value["FAmountFor"];
        }                           
        $temp["entryVoucher"][]=$value;
    }
    $temp["FEntryCount"]=$FEntryCount;
    $temp["FDebitTotal"]=round($FDebitTotal,2);
    $temp["FCreditTotal"]=round($FCreditTotal,2);
    $finally["mainVoucher"][]=$temp;
    return $finally;
}

function getMaintain($shop_id,$data,$date){ 
    $request = array(
        'token' => 1,
        'zhangtao' => "sqlsrv_scs",
        'params' => json_encode($data),
    );

    $response = Httpful::post(Config::get('config.kingdee_local_api')."/kingdeescs/importVoucher")
        ->timeoutIn(15)
        ->body($request)
        ->sendsForm()->send();

    $response = json_decode($response->body);
    Log::info($response->msg);
    $kvs=new KingdeeVoucherStatus();
    $kvs->date=$date;
    $kvs->shop_id=$shop_id;
    $kvs->type="month_jiezhuan";
    if($response->code==0){//说明成功
        $kvs->status=1;
    }else{
        $kvs->status=0;
    }
    $kvs->save();
}